package codetop;

import java.util.*;

public class lc102_level {
      static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    public List<List<Integer>> levelOrder(TreeNode root) {
          List<List<Integer>> ans = new ArrayList<>();
          Queue<TreeNode> queue = new LinkedList<>();
          if(root == null)
              return ans;
          queue.add(root);
          while(!queue.isEmpty()){
              List<Integer> list = new ArrayList<>();
              int s = queue.size();
              for (int i = 0; i < s; i++) {
                  TreeNode node = queue.poll();
                  list.add(node.val);
                  if(node.left != null) {
                      queue.add(node.left);
                  }
                  if(node.right != null){
                      queue.add(node.right);
                  }
              }
              ans.add(list);
          }
          return ans;
    }
}
